import { ref, onMounted, onUnmounted, computed, toRef } from "vue";
const todoArray = ["all", "active", "completed"]

export function useFilter(todoRef) {
    // 首先拿到变化的哈希
    const hashRef = ref("all")
    function hashChange() {
        // console.log('hash change');
        hashRef.value = location.hash.replace(/#\/?/, "")
        // console.log(hashRef.value);
        if(!todoArray.includes(hashRef.value)) {
            location.hash = "all"
        }
    }
    onMounted(() => {
        window.addEventListener("hashchange", hashChange)
    }) 
    onUnmounted(() => {
        window.removeEventListener("hashchange", hashChange)
    })

    // 需要根据哈希来筛选对应的数组
    function filterArr(todos, condition = "all") {
        // console.log(condition);
        if(condition === "all") {
            return todos
        } else if(condition === "active") {
            return todos.filter((todo) => !todo.completed)
        } else if(condition === "completed") {
            return todos.filter((todo) => todo.completed)
        } else {
            throw new Error("hash value invalid");
        }
    }

    // 需要一个计算属性来提供变化的数组
    const computedArray = computed(() => {
        // console.log(hashRef.value);
        return filterArr(todoRef.value, hashRef.value)
    })

    const remainingRef = computed(() => {
        // console.log(filterArr(todoRef.value, "active").length);
        return filterArr(todoRef.value, "active").length
    })

    const completedRef = computed(() => {
        return filterArr(todoRef.value, "completed").length
    })

    return {
        hashRef,
        computedArray,
        remainingRef,
        completedRef
    }
}